import router, { resetRouter } from "./router";
import store from "@/store";
import { AsyncRouterMap, errRouter } from "@/config/router.config";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import menu from "@/api/settings/menu";
import Layout from "@/Layout";
import tableBasic from "@/Layout/tableBasic";
import Normal from "@/Layout/Normal";
import subTable from "@/Layout/subTable";

import user from "@/api/user";

router.beforeEach(async (to, from, next) => {
  window.document.title = `${to.meta.title || "loading.."} – 复杂之眼`;
  NProgress.start();
  const nextRouter = () => {
    const is_next = () => {
      if (to.name === "Login") {
        next({
          path: store.state.menuData[0].path
        });
      } else {
        next();
      }
    };
    to.path === "/"
      ? next({
          path: store.state.menuData[0].path
        })
      : is_next();
    NProgress.done();
  };
  const pushRouter = async () => {
    let AsyncMenuData = await menu
      .index()
      .then(res => {
        return res.data.data;
      })
      .catch(() => {
        return [];
      });
    // 接口设置页面权限
    let value = await menu
      .getPermit()
      .then(res => {
        return res.data.message;
      })
      .catch(() => {
        return false;
      });

    resetRouter();
    let menuData = filter(AsyncMenuData, is_login.role_en);

    // 如果没有权限，修改权限
    let pre = [];
    let sonIndex = 0;
    if (!value) {
      pre = menuData.filter(item => {
        return item.is_get == true;
      });
      pre.forEach((item, index) => {
        item.children.filter((item, index) => {
          if (item.is_get == true) {
            sonIndex = index;
          }
          return item.is_get == true;
        });
        item.children.splice(sonIndex, 1);
      });
    }

    AsyncRouterMap[0].children = menuData;

    const accessRoutes = AsyncRouterMap.concat(errRouter);
    accessRoutes.forEach(e => {
      router.addRoute(e);
    });
    await store.dispatch("setMenuData", menuData);

    next({
      ...to,
      replace: true
    });
  };

  let is_login = await user
    .info()
    .then(res => {
      return res.data;
    })
    .catch(() => {
      return false;
    });

  const pass = async () => {
    let route = await store.state.menuData;
    const hasRouters = route && route.length > 0; // 检查是否添加路由
    hasRouters ? nextRouter() : pushRouter();
  };

  const reLogin = () => {
    to.path === "/login" ? next() : next("/login");
    NProgress.done();
  };
  is_login ? pass() : reLogin();
});

router.afterEach(() => {
  NProgress.done();
});

/**
 * 格式化过滤菜单数据 并返回到路由
 * @param asyncRouterMap 异步菜单数据
 * @param permission 权限表
 * @returns {*}
 */
export function filter(asyncRouterMap, permission) {
  return asyncRouterMap.filter(route => {
    if (
      Array.isArray(route.meta.permissions) &&
      route.meta.permissions.indexOf(permission) === -1
    ) {
      return false;
    }
    let componentName = route.component;
    if (route.component) {
      let Module = {
        Layout: Layout,
        tableBasic: tableBasic,
        Normal: Normal,
        subTable: subTable,
        default: () => import("@/views/" + componentName)
      };
      route.component = Module[componentName] || Module["default"];
    } else {
      return false;
    }

    if (route.children && route.children.length) {
      route.children = filter(route.children, permission);
    }
    return true;
  });
}
